package com.afd.ozblip.net;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;

/**
 * Http客户端对象工厂类
 * 
 * @author 徐鹏
 * 
 */
public class HttpClientFactory {

	/**
	 * http实例化
	 * 
	 * @param paramInt
	 *            超时时间（毫秒）
	 * @return
	 */
	public static HttpClient newInstance(int timeout) {
		// 获取HTTP基本参数
		BasicHttpParams localBasicHttpParams = new BasicHttpParams();
		// 设置HTTP协议参数中的版本
		HttpProtocolParams.setVersion(localBasicHttpParams,
				HttpVersion.HTTP_1_1);
		// 设置HTTP协议参数中的字符编码
		HttpProtocolParams.setContentCharset(localBasicHttpParams, "UTF-8");
		// 设置HTTP协议参数中连接超时
		HttpConnectionParams
				.setConnectionTimeout(localBasicHttpParams, timeout);
		// 禁用Nagle算法,提供性能，增大带宽消耗
		HttpConnectionParams.setTcpNoDelay(localBasicHttpParams, false);
		// 实例化一个空计划注册表
		SchemeRegistry localSchemeRegistry = new SchemeRegistry();
		localSchemeRegistry.register(new Scheme("http",
				new PlainSocketFactory(), 80));
		// 设置最大连接数为30
		ConnManagerParams.setMaxTotalConnections(localBasicHttpParams, 30);
		// 设置路由最大连接
		ConnManagerParams.setMaxConnectionsPerRoute(localBasicHttpParams,
				new AndhatConnPerRoute());
		// 返回client
		return new DefaultHttpClient(new ThreadSafeClientConnManager(
				localBasicHttpParams, localSchemeRegistry),
				localBasicHttpParams);
	}

}